
package day14;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public
class Server2 {
    static
    List<Socket> list=new ArrayList<>();//存储每个客户端的连接对象
    public static
    void main(String[] args) throws IOException {
        ServerSocket server=new ServerSocket(9997);
        while (true) {
            Socket client=server.accept();//阻塞式方法  等待客户端连接
            list.add(client);//将每个客户端的连接对象保存起来
            System.out.println("当前在线人数："+list.size());
            new ServerThread2(client).start();
        }
    }
}
class ServerThread2 extends Thread {
    Socket client;
    public ServerThread2(Socket client){
        this.client=client;
    }
    public void run() {
        try {
            BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
            while (true){
                String msg=br.readLine();
                if(msg!=null){
                    System.out.println(msg);
                    if(msg.contains("esc")){//退出聊天室功能
                        Server2.list.remove(client);
                        System.out.println("当前在线人数："+Server2.list.size());
                        break;
                    }
                    //向其他用户写入
                    for (Socket s:Server2.list){
                        if(s!=client){
                            OutputStream os=s.getOutputStream();
                            os.write((msg+"\n").getBytes());
                        }
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("连接异常：" + e.getMessage());
        } finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}